'use strict';

const axios =require("axios");

/**
 * Parent.js controller
 *
 * @description: A set of functions called "actions" for managing `Parent`.
 */

module.exports = {
    findByCode:async (ctx) =>{
        const code = ctx.params.code;
        const url = 'https://api.weixin.qq.com/sns/oauth2/access_token' +
            '?appid=wx0f8856d0e95f7eec&secret=cc85e09fca339df80c860a1c073f149f' +
            `&code=${code}&grant_type=authorization_code`;
        const response = await axios.get(url);
        const {openid:openId} = response.data;
        if(!openId) return ctx.notFound();
        let parent = await strapi.services.parent.fetch({openId});
        if(!parent) parent = await strapi.services.parent.add({openId});
        const students = await strapi.services.student.fetchAll({tel:parent.tel});
        const names = students.map(item=>item.name).join('、');
        return ctx.send({
            parent,
            students:names
        });
    },
    bind: async (ctx) =>{
        const { _id, tel } = ctx.request.body;
        const params = { tel };
        const parent = await strapi.services.parent.edit({_id},params);
        const students = await strapi.services.student.fetchAll({tel:parent.tel});
        const names = students.map(item=>item.name).join('、');
        return ctx.send({
            parent,
            students:names
        });
    },

  /**
   * Retrieve parent records.
   *
   * @return {Object|Array}
   */

  find: async (ctx) => {
    if (ctx.query._q) {
      return strapi.services.parent.search(ctx.query);
    } else {
      return strapi.services.parent.fetchAll(ctx.query);
    }
  },

  /**
   * Retrieve a parent record.
   *
   * @return {Object}
   */

  findOne: async (ctx) => {
    if (!ctx.params._id.match(/^[0-9a-fA-F]{24}$/)) {
      return ctx.notFound();
    }

    return strapi.services.parent.fetch(ctx.params);
  },

  /**
   * Count parent records.
   *
   * @return {Number}
   */

  count: async (ctx) => {
    return strapi.services.parent.count(ctx.query);
  },

  /**
   * Create a/an parent record.
   *
   * @return {Object}
   */

  create: async (ctx) => {
    return strapi.services.parent.add(ctx.request.body);
  },

  /**
   * Update a/an parent record.
   *
   * @return {Object}
   */

  update: async (ctx, next) => {
    return strapi.services.parent.edit(ctx.params, ctx.request.body) ;
  },

  /**
   * Destroy a/an parent record.
   *
   * @return {Object}
   */

  destroy: async (ctx, next) => {
    return strapi.services.parent.remove(ctx.params);
  }
};
